﻿#coding:utf-8
#功能模块化，函数                                                                                                                    #                                                                
#                                                                                                                   # 
#                                                                                                                   #
#                                                                                                                   #
#                                                                                                                   #
#                                                                                                                   #
#                                                                                                                   #
#-------------------------------------------------------------------------------------------------------------------#
from tubish.web.models import *
from tubish.web.forms import *

from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response#
from django.http import Http404

from django.contrib.auth import *
from django.contrib.auth.decorators import *

from django.utils import simplejson
from django.core import serializers

from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.graphics.shapes import * #Drawing画布 String PolyLine
from reportlab.graphics import renderPDF
import logging


        
        
def getpdf(request):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=hello.pdf'
    '''
    # Create the PDF object, using the response object as its "file."
    p = canvas.Canvas(response)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(500, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()
   
    d=Drawing(100,100)
    s=String(50,50,'hello,world',textAnchor='middle')
    d.add(s)
    '''
    data=[
    #year month predicted high low
     (2011,11,120.1,121.1,119.1),
     (2011, 12, 125.2,128.1 ,126.1),
     (2012, 1, 129.1,129.1 ,158.1),
     (2012, 2, 135.1,145.1 ,158.1),
     (2012, 3, 154.1,149.1 ,115.1),
     (2012, 4, 186.1,128.1 ,189.1),
     (2012, 5, 155.1,156.1 ,158.1),
    ]
    
    d=Drawing(300,150)
    pred=[row[2]-40 for row in data]
    high=[row[3]-40 for row in data]
    low=[row[4]-40 for row in data]
    times=[150*((row[0]+row[1]/12.0)-2011) for row in data]
    
    d.add(PolyLine(zip(times,pred),strokeColor=colors.blue))
    d.add(PolyLine(zip(times,high),strokeColor=colors.red))
    d.add(PolyLine(zip(times,low),strokeColor=colors.green))
    d.add(String(65,115,'sunpots'))
    
    renderPDF.drawToFile(d,response,'a simple pdf')
    return response
#---------------------------------------------------module1start----------------------------------------------------------#
def pager(list,page):
    
    page_size=1
    paginator = Paginator(list,page_size)
    range_size=5
    
    try:
        books= paginator.page(page)
       
        
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        page=1
        books= paginator.page(1)
        
    if paginator.num_pages>range_size:
        if page<=5:
            page_range = paginator.page_range[0:5]
        elif page>=paginator.num_pages-5:
            page_range = paginator.page_range[paginator.num_pages-5:paginator.num_pages]
        else:
            page_range = paginator.page_range[page-2:page+3]
    else:
        page_range = paginator.page_range[0:paginator.num_pages]
    result={'books':books,'range':page_range,'sum_page':paginator.num_pages,'current_page':page,'next_page':page+1,'sum':paginator.count}
    return result
#---------------------------------------------------module1end----------------------------------------------------------#
#---------------------------------------------------module2start----------------------------------------------------------#    
def index(request):
    #request.session.get('foo',False)
    user=request.user
    try:
    
        topic1=Book.objects.filter(topic__exact='topic1')[0:4]
        list1={'topic':TopicType.objects.filter(topic__exact='topic1')[0],'topic_items':topic1,}
    except:
        list1={'topic':'error,未创建','topic_items':[]}
    try:
    
        topic2=Book.objects.filter(topic__exact='topic2')[0:4]
        list2={'topic':TopicType.objects.filter(topic__exact='topic2')[0],'topic_items':topic2,}
    except:
        list2={'topic':'error,未创建','topic_items':[]}
    try:
    
        topic3=Book.objects.filter(topic__exact='topic3')[0:4]
        list3={'topic':TopicType.objects.filter(topic__exact='topic3')[0],'topic_items':topic3,}
    except:
        list3={'topic':'error,未创建','topic_items':[]}
    #lowprice_book=Book.objects.filter(topic__='topic3')[0:4]
    cart=request.session.get('cart',None)
    book_sum=Book.objects.all().count()   
    lowprice_book=BookInfo().get_lowbook(50)[0:5]
    return render_to_response('index.html', locals())
def typepager(request):
    user=request.user
    cart=request.session.get('cart',None)
    try:
        type=request.GET.get("type",'')
        page = int(request.GET.get("page",1))
        if page < 1:
            page = 1
    except ValueError:
        page = 1  
    
    if type=='topic1':
        list=Book.objects.filter(topic__exact=type)
        
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    elif type=='topic2':
        list=Book.objects.filter(topic__exact=type)
        
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    elif type=='topic3':
        list=Book.objects.filter(topic__exact=type)
        
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    elif type=='low':
        list=BookInfo().get_lowbook(50)
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    elif type=='bestseller':
        list=BookInfo().get_bestseller(50)
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    elif type=='search':
        cpath=request.GET.get('cPath','')
        key=request.GET.get('keywords','')
        if cpath:
           
            list=BookType.objects.filter(booktype__exact=cpath)[0].book_set.filter(bookname__icontains=key)
        else:
            list=Book.objects.filter(bookname__icontains=key)
            
        result=pager(list,page)
        return render_to_response('index_pager.html', locals())
    
    else:
        
        return render_to_response('404.html')
   
    


#---------------------------------------------------module2end------------------------------------------------------------#


#---------------------------------------------------module3start----------------------------------------------------------#

def register(request):
    if request.method == 'POST': # If the form has been submitted...
        form = RegisterForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            #User(username=username,password=password,email=email).save()
            

            User.objects.create_user(username=username,password=password,email=email).save()
            user = authenticate(username=username, password=password)
            login(request, user)
            
            return HttpResponseRedirect('/') # Redirect after POST
            
    else:
        form = RegisterForm()
    
    
    return render_to_response('register.html', {'form': form,})
    
    
    

    
def mylogin(request):
    case=False
    if request.method == 'POST': # If the form has been submitted...
        form = LoginForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # Correct password, and the user is marked "active"
                login(request, user)
                # Redirect to a success page.
                
                return HttpResponseRedirect("/")#
            else:
                case=True;form = LoginForm()
                
                #form = LoginForm()
                #return HttpResponseRedirect("/account/invalid/")
            
            
            
    else:
        form = LoginForm()
    
    
    return render_to_response('login.html', {'form': form,'case':case})

def logout(request):
    #id=requset.user.id
    #requset.session.clear()
    #logout(request)
    
    request.session.clear()
    #del(request.session['user'])
    return HttpResponseRedirect("/")
def showinfo(request):
    user=request.user
    
    
    return render_to_response('404.html')  
#---------------------------------------------------module3end------------------------------------------------------------#

#---------------------------------------------------module4start----------------------------------------------------------#    
def search(request):
    if request.method=='GET':
        x=request.GET.get('CPath',"")
        print x
        return render_to_response('books.html', locals())
    else:
        return render_to_response('books.html', locals())

def bookpager(request):
    pass
def showbook(request):
    user=request.user
    cart=request.session.get('cart',None)
    bookid=request.GET.get('id')
    
    try :
        book=Book.objects.all().get(id__exact=bookid)
    except:
        book=Book.objects.all().get(id__exact=1)
    return render_to_response('book_info.html', locals())
#---------------------------------------------------module4end------------------------------------------------------------#    
#---------------------------------------------------module5start----------------------------------------------------------#

def addcart(request):
    
    try: 
        request.session['cart']
    except:
        
        request.session['cart']=Cart()
    result=None   
    if request.method=='POST':
            id=request.POST.get("bookid","")
            try:
                book=Book.objects.get(id__exact=id)
            except:
                return render_to_response('404.html') 
            cart=request.session['cart']
            cart.add_product(book)
            request.session['cart']=cart
            return render_to_response('cart_success.html', locals())
           
        
            
    
        
    
    elif request.is_ajax:
        bookid=request.GET.get('used_id','')
        
        
        
        if bookid:
            b=Book.objects.get(id__exact=bookid)
            cart=request.session['cart']
            cart.add_product(b)
            request.session['cart']=cart
            num=cart.get_sumitems()
            #print num*
            result='共'+str(num)+'件商品,总价:'+str(cart.total_price)
            return HttpResponse(result)
            #logging.debug("run 2")
        else:
            cart=request.session['cart']
            num=cart.get_sumitems()
            #print num*
            result='共'+str(num)+'件商品,总价:'+str(cart.total_price)
            return HttpResponse(result)
    else:
        return render_to_response('404.html') 
        
    
def delcart(request):
    id=request.GET.get('bookid','')
    b=Book.objects.get(id__exact=id)
    print id,"&*&***&*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&**************8"
    cart=request.session['cart']
    cart.del_product(b)
    request.session['cart']=cart
    
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def showcart(request):
    user=request.user
    cart=request.session.get('cart',None)
    
    
    return render_to_response('shopping_cart.html',locals())
def updatecart(request):
    pass
#---------------------------------------------------module5start----------------------------------------------------------#

#---------------------------------------------------module6start----------------------------------------------------------#
def checkout(request):
    pass


#---------------------------------------------------module6end-------------------------------------------------------------#
    
  